package com.zsyc.controller;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.zsyc.model.Task;
import java.util.ArrayList;

/**
 * 任务管理控制器类
 */
public class TaskManagementController {
    private static final Logger LOGGER = Logger.getLogger(TaskManagementController.class.getName());
    
    @FXML private TextField titleInput;
    @FXML private TextArea descriptionInput;
    @FXML private DatePicker dueDatePicker;
    @FXML private ComboBox<String> categoryCombo;
    @FXML private Button addTaskButton;
    @FXML private CheckBox enableReminderCheck;
    @FXML private VBox reminderSettingsContainer;
    @FXML private Spinner<Integer> reminderTimeSpinner;
    @FXML private ComboBox<String> reminderUnitCombo;
    @FXML private ComboBox<String> filterCategoryCombo;
    @FXML private Button filterButton;
    @FXML private Button clearFilterButton;
    @FXML private TableView<Task> taskTableView;
    @FXML private TableColumn<Task, Integer> idColumn;
    @FXML private TableColumn<Task, String> titleColumn;
    @FXML private TableColumn<Task, String> descriptionColumn;
    @FXML private TableColumn<Task, LocalDate> dueDateColumn;
    @FXML private TableColumn<Task, String> categoryColumn;
    @FXML private TableColumn<Task, Boolean> statusColumn;
    @FXML private TableColumn<Task, String> actionColumn;
    
    private MainController mainController;
    private ObservableList<Task> taskList;
    private ObservableList<String> categoryList;
    
    /**
     * 初始化控制器
     */
    @FXML
    public void initialize() {
        setupTaskTable();
        setupCategoryCombo();
        setupFilterCombo();
        setupReminderSettings();
        loadTasks();
    }
    
    /**
     * 设置主控制器引用
     */
    public void setMainController(MainController mainController) {
        this.mainController = mainController;
    }
    
    /**
     * 设置任务表格
     */
    private void setupTaskTable() {
        taskList = FXCollections.observableArrayList();
        
        idColumn.setCellValueFactory(new PropertyValueFactory<>("taskId"));
        titleColumn.setCellValueFactory(new PropertyValueFactory<>("title"));
        descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        dueDateColumn.setCellValueFactory(new PropertyValueFactory<>("dueDate"));
        categoryColumn.setCellValueFactory(new PropertyValueFactory<>("category"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("completed"));
        
        // 设置操作列
        actionColumn.setCellFactory(param -> new TableCell<>() {
            private final HBox buttonBox = new HBox(5);
            private final Button editButton = new Button("编辑");
            private final Button deleteButton = new Button("删除");
            private final CheckBox completeCheckBox = new CheckBox("完成");
            
            {
                editButton.setStyle("-fx-background-color: #f39c12; -fx-text-fill: white;");
                deleteButton.setStyle("-fx-background-color: #e74c3c; -fx-text-fill: white;");
                
                editButton.setOnAction(event -> {
                    Task task = getTableView().getItems().get(getIndex());
                    editTask(task);
                });
                
                deleteButton.setOnAction(event -> {
                    Task task = getTableView().getItems().get(getIndex());
                    deleteTask(task);
                });
                
                completeCheckBox.setOnAction(event -> {
                    Task task = getTableView().getItems().get(getIndex());
                    toggleTaskStatus(task);
                });
                
                buttonBox.getChildren().addAll(editButton, deleteButton, completeCheckBox);
            }
            
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(buttonBox);
                }
            }
        });
        
        taskTableView.setItems(taskList);
    }
    
    /**
     * 设置分类下拉框
     */
    private void setupCategoryCombo() {
        categoryList = FXCollections.observableArrayList("工作", "学习", "生活", "其他");
        categoryCombo.setItems(categoryList);
        categoryCombo.setValue("工作");
    }
    
    /**
     * 设置筛选下拉框
     */
    private void setupFilterCombo() {
        filterCategoryCombo.setItems(categoryList);
        filterCategoryCombo.getItems().add(0, "全部");
        filterCategoryCombo.setValue("全部");
    }
    
    /**
     * 设置提醒功能
     */
    private void setupReminderSettings() {
        reminderUnitCombo.setItems(FXCollections.observableArrayList("小时", "天"));
        reminderUnitCombo.setValue("小时");
        
        enableReminderCheck.selectedProperty().addListener((obs, oldVal, newVal) -> {
            reminderSettingsContainer.setDisable(!newVal);
        });
    }
    
    /**
     * 加载任务列表
     */
    private void loadTasks() {
        taskList.clear();
        List<Task> tasks = Task.getAllTasks();
        taskList.addAll(tasks);
    }
    
    /**
     * 添加任务
     */
    @FXML
    private void addTask() {
        String title = titleInput.getText().trim();
        String description = descriptionInput.getText().trim();
        LocalDate dueDate = dueDatePicker.getValue();
        String category = categoryCombo.getValue();
        
        if (title.isEmpty()) {
            showAlert("输入错误", "请输入任务标题。", Alert.AlertType.WARNING);
            return;
        }
        
        boolean enableReminder = enableReminderCheck.isSelected();
        int reminderTime = reminderTimeSpinner.getValue();
        String reminderUnit = reminderUnitCombo.getValue();
        
        Task task = new Task(title, description, dueDate, category, enableReminder, reminderTime, reminderUnit);
        
        try {
            if (task.save()) {
                showAlert("添加成功", "任务添加成功。", Alert.AlertType.INFORMATION);
                clearInputs();
                loadTasks();
            } else {
                showAlert("添加失败", "任务添加失败，请检查数据库连接。", Alert.AlertType.ERROR);
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "添加任务时发生异常", e);
            showAlert("添加失败", "添加任务时发生错误：" + e.getMessage(), Alert.AlertType.ERROR);
        }
    }
    
    /**
     * 编辑任务
     */
    private void editTask(Task task) {
        // 这里可以实现编辑对话框
        showAlert("编辑功能", "编辑功能正在开发中...", Alert.AlertType.INFORMATION);
    }
    
    /**
     * 删除任务
     */
    private void deleteTask(Task task) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除任务");
        alert.setContentText("确定要删除任务 \"" + task.getTitle() + "\" 吗？");
        
        if (alert.showAndWait().orElse(null) == ButtonType.OK) {
            if (task.delete()) {
                showAlert("删除成功", "任务删除成功。", Alert.AlertType.INFORMATION);
                loadTasks();
            } else {
                showAlert("删除失败", "任务删除失败。", Alert.AlertType.ERROR);
            }
        }
    }
    
    /**
     * 切换任务状态
     */
    private void toggleTaskStatus(Task task) {
        task.setCompleted(!task.isCompleted());
        if (task.update()) {
            loadTasks();
        } else {
            showAlert("更新失败", "无法更新任务状态。", Alert.AlertType.ERROR);
        }
    }
    
    /**
     * 筛选任务
     */
    @FXML
    private void filterTasks() {
        String selectedCategory = filterCategoryCombo.getValue();
        
        if ("全部".equals(selectedCategory)) {
            loadTasks();
        } else {
            taskList.clear();
            List<Task> tasks = Task.getTasksByCategory(selectedCategory);
            taskList.addAll(tasks);
        }
    }
    
    /**
     * 清除筛选
     */
    @FXML
    private void clearFilter() {
        filterCategoryCombo.setValue("全部");
        loadTasks();
    }
    
    /**
     * 清空输入框
     */
    private void clearInputs() {
        titleInput.clear();
        descriptionInput.clear();
        dueDatePicker.setValue(null);
        categoryCombo.setValue("工作");
        enableReminderCheck.setSelected(false);
        reminderTimeSpinner.getValueFactory().setValue(2);
        reminderUnitCombo.setValue("小时");
    }
    
    /**
     * 提醒设置改变事件
     */
    @FXML
    private void onReminderSettingChanged() {
        reminderSettingsContainer.setDisable(!enableReminderCheck.isSelected());
    }
    
    /**
     * 返回主页
     */
    @FXML
    private void goBack() {
        if (mainController != null) {
            mainController.showMainView();
        } else {
            LOGGER.warning("主控制器引用为空，无法返回主页");
        }
    }
    
    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String content, Alert.AlertType type) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}
